<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="班次名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入班次名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="班次状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="timeShiftList">
      <el-table-column label="班次编号" prop="id" width="100"/>
      <el-table-column label="班次类型" prop="type" width="80" v-if="show"/>
      <el-table-column label="班次名称" prop="name" :show-overflow-tooltip="true" width="120"/>
      <!-- 1.2需求变更 -->
      <!-- <el-table-column label="工作开始时间" prop="beginTime" :show-overflow-tooltip="true" width="120"/> -->
      <el-table-column label="工作时间" prop="beginTime" :show-overflow-tooltip="true" width="200"/>
      <el-table-column label="描述" prop="describe" min-width="250"/>
      <!-- <el-table-column label="价格(元)" prop="price" :show-overflow-tooltip="true" width="100"/> -->
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="2"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" width="150"/> -->
      <el-table-column label="班次间隔" prop="threshold" width="80" v-if="show"/>
      <el-table-column label="创建时间" prop="createTime" width="200" v-if="show">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="剩余名额" prop="number" width="180">-->
      <!--        <template slot-scope="{row,$index}">-->
      <!--          <input class="edit-cell"    v-model="row.number" @change="saveNeedNumber(row.type,row.number)">-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-medal-1"
            @click="modifyPrice(scope.row)"
          >改价格
          </el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改班次对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form"  :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="班次名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入班次名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次类型" prop="type">
              <el-input v-model="form.type" placeholder="请输入班次类型"/>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="班次阈值" prop="threshold">
              <el-input v-model="form.threshold" placeholder="请输入班次阈值"/>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="班次开始时间" prop="beginTime">
              <el-input v-model="form.beginTime" placeholder="请输入班次开始时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次描述" prop="describe">
              <el-input v-model="form.describe" placeholder="请输入班次描述"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.label"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注"/>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改价格对话框 -->
    <el-dialog :title="priceForm.title" :visible.sync="priceFormOpen" width="780px" :showClose="false" append-to-body>
      <el-form ref="priceForm" :model="priceForm" label-width="80px" >
        <el-row>
          <el-col :span="12">
            <el-form-item label="班次" prop="name">
              <el-input v-model="priceForm.name" disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="priceForm.price" placeholder="请输入价格">
                <i slot="suffix" style="margin-right: 10px;">元</i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPriceForm">确 定</el-button>
        <el-button @click="priceFormCancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-alert
      title="请输入签到码"
      type="error"
      v-if="flag"
      center
    >
    </el-alert>
    <!-- <el-row :gutter="15" class="mb8">
      <el-col :span="4">
        <div class="grid-content bg-purple">签到/签退二维码</div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <el-input v-model="qrCode" placeholder="qd/qt时间 例:qd20210829"></el-input>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <el-button type="text" @click="qrCodeDialogVisible = true">查看二维码</el-button>
        </div>
      </el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <el-button @click="downLoad" class="nowBtn">二维码下载</el-button>
        </div>
      </el-col>

      <el-col :span="4">
        <div class="grid-content bg-purple">
          <el-button @click="handleImport" class="nowBtn">导入excel</el-button>
        </div>
      </el-col>
    </el-row>
    -->
    <el-dialog
      title="签到/签退二维码预览"
      :visible.sync="qrCodeDialogVisible"
      width="40%"
      @opened="qrCodeCreate"
      :before-close="qrCodeHandleClose">
      <div style="margin-left: 10%">
        <div id="qrCode" ref="qrCode"></div>
      </div>
    </el-dialog>
    <div id="qrcodes"></div>


    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        multiple
        :file-list="fileList"
        :limit="2"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-change="beforeUpload"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。并且两个文件中要存在相同身份证的数据</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">导 入</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>


</template>

<script>
import QRCode from 'qrcodejs2';
import md5 from 'js-md5';
import {getToken} from "@/utils/auth";
import {
  listTimeShiftList,
  changeStatus,
  insert,
  getTimeShift,
  delTimeShift,
  update,
  saveNumber,
  upload
} from '@/api/job/jobset/jobSet'

export default {
  name: "index",
  props: {
    /* 上传框提示 */
    promptMessage: {
      default: '只能上传xls/xlsx文件',
      type: String
    },
    /* 文件上传路径 */
    uploadAction: {
      default: '',
      type: String
    },
    /* 文件类型 */
    fileType: {
      default: '.xlsx,.xls',
      type: String
    },
    /* 限制最大文件上传数 */
    fileSizeLimit: {
      default: 2,
      type: Number
    }
  },
  data() {
    return {
      show: false,
      fileList: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "工具类导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: "/excelToolApi/importData"
      },
      showEdit: [],
      needNumber: 0,
      // 遮罩层
      qrCode: "",
      qrCodeDialogVisible: false,
      flag: false,
      loading: true,
      // 总条数
      total: 0,
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      priceFormOpen:false,
      priceForm:{
        // 是否显示弹出层（用户导入）
        // 弹出层标题（用户导入）
        title: "修改价格",
      },
      fileName:"",
      timeShiftList: [],
      statusOptions: [{value: 1, label: '启用'}, {value: 2, label: '停用'}],
      rules: {
        name: [
          { required: true, message: "班次名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '班次名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        type: [
          { required: true, type:'number',message: "班次类型不能为空且需为数字", trigger: "blur" ,transform: (value) => Number(value)}
        ],
        threshold: [
          { required: true, type:'number',message: "班次阈值不能为空且需为数字", trigger: "blur" ,transform: (value) => Number(value)}
        ],
        describe: [
          { required: true, message: "班次描述不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '班次描述长度必须介于 2 和 20 之间', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    qrCodeHandleClose() {
      this.qrCodeDialogVisible = false;
      this.qrCode = '';
      document.getElementById('qrCode').innerHTML = '';
    },
//创建二维码
    qrcode(qrCode, code) {
      this.qrCode = new QRCode(qrCode, {
        text: code,
        width: 400,
        height: 400
      })
    },
    qrCodeCreate() {
      if (this.qrCode == '') {
        this.flag = true;
        return;
      }
      let qrCodes = md5('zkzn' + this.qrCode);
      this.$nextTick(() => {
        this.qrcode('qrCode', qrCodes);
      })
    },


    downLoad() {
      if (this.qrCode == '') {
        this.flag = true;
        return;
      }
      this.qrcode('qrcodes', md5('zkzn' + this.qrCode));
      let myCanvas = document.getElementById('qrcodes').getElementsByTagName('canvas');
      let a = document.createElement('a')
      a.href = myCanvas[0].toDataURL('image/png');
      a.download = '二维码';
      a.click()
      this.$message({
        message: "正在进行下载保存",
        type: 'success'
      })
      document.getElementById('qrcodes').innerHTML = '';
      this.qrCode = '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    priceFormCancel(){
      this.priceFormOpen= false;
    },
// 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        type: undefined,
        status: undefined,
        createTime: undefined,
      };
      this.resetForm("form");
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listTimeShiftList(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.timeShiftList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    handleStatusChange(row) {
      let text = row.status === "1" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.name + '"角色吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return changeStatus(row.id, row.status);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + id + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delTimeShift(id);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            update(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            insert(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加渠道信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTimeShift(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "班次信息";
      });
    },
    modifyPrice(row) {
      this.reset();
      const id = row.id || this.ids
      getTimeShift(id).then(response => {
        this.priceForm = response.data;
        this.priceFormOpen = true;
      });
    },

    /** 提交按钮 */
    submitPriceForm: function () {
      this.$refs["priceForm"].validate(valid => {
        if (valid) {
          update(this.priceForm).then(response => {
            this.msgSuccess("修改成功");
            this.priceFormOpen = false;
            this.getList();
          });
        }
      });
    },

    saveNeedNumber(type, event) {

      saveNumber(type, event).then(response => {
        this.msgSuccess("报名名额设置成功");
        this.getList();
      })
    },
    handleImport() {
      this.upload.title = "工具类数据合并";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
    },
    submitFileForm() {
      upload(this.upload.url,this.fileList).then(res => {
        this.fileList = [];
        this.download(res.msg);
      });
    },
    beforeUpload(file,fileList) {
      // 1、判断文件名是否重复，不允许上传相同文件
      let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
      if(existFile){
        fileList.pop()
      }
      // 2、获取文件后缀
      fileList.forEach(everyFile => {
        const fileType = everyFile.name.substring(everyFile.name.lastIndexOf('.'))
        if(this.fileType.search(fileType) === -1){
          fileList.pop()
        }
      })
      this.fileList = fileList;
    }
  }
}
</script>

<style scoped>

</style>
